#include "../include/defs.h"
#include "../include/kernel.h"
#include "../include/malloc.h"
#include "../include/string.h"
#include "../include/kasm.h"


/* Page Table */
extern unsigned long *page_table;
extern unsigned long *page_table2;
extern int page_pid[CANT_PAGES];

extern int CurrentPID;


int nextfree=0x300000;

//Proceso Malloc
void *
Malloc (int size)
{
    void* temp = (void*)nextfree;
    nextfree=nextfree+size;
    return temp;
}

// Malloc inicializado en 0
void *
Calloc (int size)
{
    char* temp;
    int i;
    temp=(char*)Malloc(size);
    for(i=0;i<size;i++)
        temp[i]=0;
    return (void*)temp;
}

//Malloc para zonas de video, inicializa en {0007}
void *
CallocVid (int size)
{
    char* temp;
    int i;
    temp=(char*)Malloc(size);
    for(i=0;i<size;i+=2)
    {
        temp[i]=0;
        temp[i+1]=0x07;
    }
    return (void*)temp;
}

void *
wMalloc (int size)
{
    int i;
    int old_ind;
    PROCESS * proc;
    int next_temp;
    int cant_need = 0;

    next_temp = nextfree % PAGE_SIZE;

    if (next_temp + size < PAGE_SIZE)
    {
        _Sti();
        return Malloc(size);

    }

    _Cli();


    cant_need = (next_temp + size) / PAGE_SIZE;
/*    if((next_temp + size) % PAGE_SIZE)
        cant_need++;
*/
    proc=GetProcessByPID(CurrentPID);
    old_ind = proc->heap_page;



    for(i = CANT_PAGES - 1 ; i > 0; i--)
    {
        if(page_pid[i] != -1)
            break;
    }
    i++;    /* La primera pagina vacia empezando desde la ultima */


    int news = i;

    nextfree = 4 * 1024 * 1024 + 4096*(news);


    while(cant_need--)
    {
//        page_pid[news] = CurrentPID;
        page_pid[news] = -(CurrentPID * 100);
        page_table2[news] = page_table2[news] | 3;
        news++;
    }


    _Sti();
    return Malloc(size);


}
